package com.lingyun.common.web.support;

import com.lingyun.common.json.AjaxUtil;
import com.lingyun.common.json.WebJsonConfig;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;

import java.util.List;

/**
 * Created by bain.wang on 2016/1/22.
 */
public class BaseController {

    /**
     * 输出spring分页结果到json
     *
     * @param page
     * @return
     */
    protected JSONObject jqGridJson(Page page) {
        return AjaxUtil.jqGridJson(page);
    }

    /**
     * 输出分页相关对象到json
     *
     * @param totalPages
     * @param pageNum
     * @param totalElements
     * @param dataList
     * @return
     */
    protected JSONObject jqGridJson(Integer totalPages, Integer pageNum, Long totalElements, List dataList) {
        JSONArray jsonArray = new JSONArray();
        if (dataList != null && dataList.size() > 0) {
            for (Object object : dataList) {
                JSONObject jsonObject = JSONObject.fromObject(object, WebJsonConfig.getInstance());
                jsonArray.add(jsonObject);
            }
        }
        return AjaxUtil.jqGridJson(totalPages, pageNum, totalElements, jsonArray);
    }


    /**
     * 输出失败到json
     *
     * @param errorCode
     * @param msg
     * @param extData
     * @return
     */
    protected JSONObject failure(Integer errorCode, String msg, Object extData) {
        if (errorCode == null) {
            errorCode = 999999;
        }
        if (StringUtils.isEmpty(msg)) {
            msg = "未知错误";
        }

        JSONObject data = null;
        if (extData != null) {
            data = JSONObject.fromObject(extData, WebJsonConfig.getInstance());
        }
        return AjaxUtil.output(false, errorCode, msg, data);
    }

    /**
     * 输出成功对象到json
     *
     * @param errorCode
     * @param msg
     * @param extData
     * @return
     */
    protected JSONObject success(Integer errorCode, String msg, Object extData) {
        if (errorCode == null) {
            errorCode = 0;
        }
        JSONObject data = null;
        if (extData != null) {
            data = JSONObject.fromObject(extData, WebJsonConfig.getInstance());
        }
        return AjaxUtil.output(false, errorCode, msg, data);
    }


}
